package server.communication.listeners;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import server.Server;
import server.repositories.AccountRepository;
import server.threads.ServerCommunicator;

import message.AuthenticationRequestMessage;
import message.AuthenticationResponseMessage;
import message.Message;
import message.ServerMessageWrapper;
import communication.MessageListener;
import communication.MessageReceivedEvent;
import entities.Account;

public class AuthenticationListener implements MessageListener
{
	private final ServerCommunicator communicator;
	private final AccountRepository accountRepository;
	
	public AuthenticationListener(ServerCommunicator communicator, AccountRepository accountRepository)
	{
		this.communicator = communicator;
		this.accountRepository = accountRepository;
	}
	
	private boolean validCrdentials(String username, String password)
	{
		Account account = accountRepository.get(username);
		
		System.out.println(account);
		
		if (account != null)
		{
			System.out.println(account.username);
			System.out.println(account.password);
		}
		
		return account != null && account.password.equals(password);
	}
	@Override
	public void messageRecieved(MessageReceivedEvent e)
	{
		ServerMessageWrapper message = ((ServerMessageWrapper) e.getMessage());
		AuthenticationRequestMessage innerMessage = (AuthenticationRequestMessage) message.internalMessage;
		AuthenticationResponseMessage responseMessage = new AuthenticationResponseMessage();
		
		responseMessage.setSuccess(validCrdentials(innerMessage.getUsername(), innerMessage.getPassword()));
		
		communicator.sendMessage(message.connectionId, responseMessage);
	}

	@Override
	public boolean acceptsMessage(Message message)
	{
		if (message.getClass().equals(ServerMessageWrapper.class))
			message = ((ServerMessageWrapper) message).internalMessage;
		
		return message.getClass().equals(AuthenticationRequestMessage.class);
	}

}
